package com.springboot.cloud.demos.feign.rest;

import com.alibaba.fastjson.JSONObject;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.demos.entity.form.FollowForm;
import com.springboot.cloud.demos.entity.param.FollowQueryParam;
import com.springboot.cloud.demos.entity.po.User;
import com.springboot.cloud.demos.feign.config.BusConfig;
import com.springboot.cloud.demos.feign.events.BusSender;
import com.springboot.cloud.demos.feign.service.FollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
public class FollowController extends BaseController {
    @Autowired
    private FollowService followService;

    @Autowired
    private BusSender busSender;

    /**
     * 关注
     */
    @RequestMapping(value = "/follow", method = RequestMethod.POST)
    public Result save(HttpServletRequest request, @RequestBody FollowForm follow) {
        User user = getUser(request);
        follow.setUserId(user.getId());

        Result result = followService.save(follow);
        if (result.isSuccess()) {
            //新建推送和消息
            String message= JSONObject.toJSONString(follow);
            busSender.send(BusConfig.EXCHANGE_NAME,"follow.message",message);
        }
        return result;
    }

    /***取消关注
     *
     * @param request
     * @param followUserId
     * @return
     */
    @RequestMapping(value = "/unFollow", method = RequestMethod.POST)
    public Result delete(HttpServletRequest request, @RequestParam String followUserId) {
        User user = getUser(request);
        FollowQueryParam queryParam = new FollowQueryParam();
        queryParam.setFollowUserId(followUserId);
        queryParam.setUserId(user.getId());
        return followService.deleteByMap(queryParam);
    }

    /***
     * 查询是否关注
     * @param request
     * @param followUserId
     * @return
     */
    @RequestMapping(value = "/follow", method = RequestMethod.GET)
    public Result query(HttpServletRequest request, @RequestParam String followUserId) {
        User user = getUser(request);
        return followService.getFollow(user.getId(), followUserId);
    }

}
